package com.schoolvisitors.service;

import com.alibaba.fastjson2.JSONObject;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriComponentsBuilder;


import java.util.Objects;

@Slf4j
@Service
public class WeChatService {

    @Value("${wechat.corpId}")
    private String corpId;

    @Value("${wechat.secret}")
    private String secret;

    private final WebClient webClient = WebClient.builder().baseUrl("https://qyapi.weixin.qq.com").build();

    @Getter
    private String accessToken;

    // 定时任务每小时刷新一次 access token
    @Scheduled(fixedDelay = 3600000)
    public void autoRefreshAccessToken() {
        this.accessToken = refreshAccessToken();
        log.info("自动刷新企业微信token");
        log.info("accessToken:{}", accessToken);

    }

    // 获取 AccessToken
    public String refreshAccessToken() {
        // 构建 URL
//        https://qyapi.weixin.qq.com?corpid=ID&=SECRET
        String url = UriComponentsBuilder.fromPath("/cgi-bin/gettoken")
                .queryParam("corpid", corpId)
                .queryParam("corpsecret", secret)
                .toUriString();

        // 发送 GET 请求并返回 Mono
        return webClient.get()
                .uri(url)
                .retrieve()
                .bodyToMono(JSONObject.class)
                .map(response -> {
                    // 解析响应并返回 access_token
                    // 这里需要解析 JSON 进行处理，可以使用 JsonParser 解析
                    return response.getString("access_token");  // 返回你解析后的access_token
                }).block();
    }

    // 获取用户信息
    public String getUserId( String code) {
        String url = UriComponentsBuilder.fromPath("/cgi-bin/auth/getuserinfo")
                .queryParam("access_token", getAccessToken())
                .queryParam("code", code)
                .toUriString();

        return Objects.requireNonNull(webClient.get()
                .uri(url)
                .retrieve()
                .bodyToMono(JSONObject.class)
                .handle((response, sink) -> {
                    log.info("{}", response.toJSONString());
                    // 返回用户信息，或者你可以进一步解析JSON响应
                    if (!response.getString("errcode").equals("0")) {
                        sink.error(new RuntimeException("企业微信获取用户信息出错: " + response.getString("errmsg")));
                        return;
                    }

                    sink.next(response.getString("userid"));
                    sink.complete();
                }).block()).toString();
    }
    // 发送纯文本消息给指定用户
    public void sendTextMessage(String weChatId, String content) {
        String url = UriComponentsBuilder.fromPath("/cgi-bin/message/send")
                .queryParam("access_token", getAccessToken())
                .toUriString();

        JSONObject text = new JSONObject();
        text.put("content", content);

        JSONObject body = new JSONObject();
        body.put("touser", weChatId);
        body.put("msgtype", "text");
        body.put("agentid", 1000262);
        body.put("text", text);

        webClient.post()
                .uri(url)
                .bodyValue(body)
                .retrieve()
                .bodyToMono(JSONObject.class)
                .doOnNext(response -> {
                    log.info("发送消息响应: {}", response.toJSONString());
                    if (!Objects.equals(response.getString("errcode"), "0")) {
                        throw new RuntimeException("发送消息失败: " + response.getString("errmsg"));
                    }
                })
                .block();
    }

}
